<template>
    <div class="play-bar" v-if="playList.playlist.length != 0" v-click-outside="lyricHanlder">
        <!-- {{ usePlayList().playlist.length }} -->
        <div class="play-main">
            <el-slider v-model="playtime" :max="pageObj.milliseconds" :format-tooltip="formatTooltip"
                @input="playtimeinput" />
            <div class="play-bar-main">
                <div class="bar-l">
                    <!-- 头像 -->
                    <el-link @click="router.push(`/song?id=${pageObj.id}`)" :underline="false">
                        <el-image :src="pageObj.album.picUrl"></el-image>
                    </el-link>
                    <div class="bar-name">
                        <!-- 歌名 -->
                        <el-link @click="router.push(`/song?id=${pageObj.id}`)" :underline="false">{{ pageObj.name
                        }}</el-link>
                        <p>
                            <!-- 歌手，循环显示 -->
                            <el-link @click="router.push(`/singer/detail?id=${singer.id}`)"
                                v-for="singer, index in pageObj.singer" :key="singer" type='info'>
                                <span v-if="index != 0">/</span> {{ singer.name }}
                            </el-link>
                        </p>
                    </div>
                    <div class="bar-time">
                        <!-- 当前播放时间 -->
                        <span>{{ formatTime(playtime) }}</span>/{{ pageObj.duration }}
                    </div>
                </div>
                <div class="bar-m">
                    <!-- 播放按钮 上一个，暂停，下一个 -->
                    <div class="bar-control">
                        <i class="iconfont icon-shangyishou" @click="changIndex(-1)" style="font-size: 30px;"></i>
                        <!-- 开始按钮 -->
                        <i class="iconfont icon-play" style="color: #409eff;font-size: 30px;" v-if="!playStatus.playStatus"
                            @click="playMusic(true)"></i>
                        <!-- 暂停按钮 -->
                        <i class="iconfont icon-pause" style="color: #409eff;font-size: 30px;" v-else
                            @click="playMusic(false)"></i>
                        <i class="iconfont icon-xiayishou" @click="changIndex(1)" style="font-size: 30px;"></i>
                    </div>
                </div>
                <div class="bar-r">
                    <div class="bar-oper">
                        <!-- 音量条 -->
                        <div class="volume-main">
                            <i class="iconfont icon-shengyin" style="font-size: 20px;"></i>
                            <el-slider v-model="volume" @input="volumeChange" />
                        </div>
                        <!-- 循环模式 -->
                        <i class="iconfont icon-xunhuanbofang" style="width: 18px;" v-if="playIndex.playMode == 0"
                            title="现在是顺序播放" @click="playIndex.playMode = 1"></i>
                        <!-- 随机播放 -->
                        <i class="iconfont icon-repeat" style="width: 18px;" v-if="playIndex.playMode == 1" title="现在是随机播放"
                            @click="playIndex.playMode = 2"></i>
                        <!-- 单曲循环 -->
                        <i class="iconfont icon-danquxunhuan" style="width: 18px;" v-if="playIndex.playMode == 2"
                            title="现在是单曲循环" @click="playIndex.playMode = 0"></i>
                        <!-- 歌词 -->
                        <div class="lyric" @click="lyricsHanlder" ref="lyricsBtnRef">
                            <span class="lyric-btn" title="歌词">词</span>
                        </div>
                        <div class="playlist-main" @click="playlistHanlder" ref="playlistBtnRef">
                            <!-- 播放列表 -->

                            <el-badge :value="playList.playlist.length" class="item" type="primary" :max="99">
                                <el-tooltip :visible="visible" trigger="contextmenu">
                                    <template #content>
                                        <span>{{ visiblename }} 添加到播放列表</span>
                                    </template>
                                    <i class="iconfont icon-list"></i>
                                </el-tooltip>
                            </el-badge>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <audio :src="pageObj.url" autoplay ref="music" @play="play" @timeupdate="timeupdate" @ended="ended"></audio>

    <el-popover placement="top-end" :show-arrow="false" :visible="isShowLyrics" :width="clickType == 'lyrics' ? 400 : 560"
        :virtual-ref="popoverBtn" :offset=20 virtual-triggering popper-style="bottom:75px;">
        <div class=" pop-main" ref="popoverRef">
            <template v-if="clickType == 'lyrics'">
                <h3 class="pop-header">
                    <span>歌词</span>
                </h3>
                <SongLyric :lyric="lyric" />
            </template>
            <template v-if="clickType == 'playlist'">
                <h3 class="pop-header">
                    <span>播放列表<em>(共{{ playList.playlist.length }}首)</em></span>
                    <div class="del-songlist" @click="clearSonglist"><i class="iconfont icon-del" title="清空列表"></i>清空列表
                    </div>
                </h3>
                <!-- <song-list :songList="playListInfoStore.playList" :typeSize="'mini'" :isScroll="true"></song-list> -->
                <SongList :songList="playList.playlist" :typeSize="'mini'" :isScroll="true" :height="400"></SongList>
            </template>
        </div>
    </el-popover>
</template>

<script setup>
import SongLyric from '@/components/song/SongLyric.vue'
import SongList from '@/components/song/SongList.vue'
import { ref, watch, onMounted } from 'vue'
import { getSongUrl, getSongLyric } from '@/api/song'
import { usePlayList, usePlayIndex, usePlayStatus, usePlayE } from '@/stores/playlist'
import { formatTime } from '@/utils/util'
import { parseLyric } from '@/utils/lyric'
import { useRoute, useRouter } from 'vue-router'
import { useUser } from '@/stores/user'
import { ElMessage } from 'element-plus'

// import { ClickOutside as vClickOutside } from 'element-plus'


const route = useRoute()
const router = useRouter()
const playStatus = usePlayStatus()
const playIndex = usePlayIndex()
const user = useUser()
const playList = usePlayList()
const playE = usePlayE()

const lyric = ref([])//歌词
const pageObj = ref({
    album: {
        picUrl: ''
    },
    singer: [],
    name: '',
    duration: '',
    id: 0,
    url: ''
})
const music = ref(null)//音乐播放器audio
const playtime = ref(0)//当前播放时间
const volume = ref(100)//音量
const isShowLyrics = ref(false)//播放列表提示框
const popoverBtn = ref(null)//播放列表提示框按钮
const clickType = ref('lyrics')//点击的类型
const visiblename = ref('')//播放列表提示框歌曲名
const visible = ref(false)//播放列表提示框
const popoverRef = ref(null)//播放列表提示框
const playlistBtnRef = ref(null)//播放列表按钮
const lyricsBtnRef = ref(null)//歌词按钮
watch(
    () => playIndex,
    async (newVal) => {
        if (playList.playlist.length == 0) return
        const index = newVal.playIndex

        const lrc = await getSongLyric(playList.playlist[newVal.playIndex].id)

        if (lrc.lrc) {
            lyric.value = parseLyric(lrc.lrc.lyric)
        } else {
            lyric.value = parseLyric("[00:00.000] 暂无歌词")
        }
        if (playList.playlist.length == 0) return

        //如果是vip歌曲，就调用getSongUrl接口获取url
        if (playList.playlist[index].vip) {
            //如果是vip歌曲，但用户不是vip，就提示用户开通vip
            if (user.user.vipType == 0 || !user.user.vipType) {
                ElMessage({
                    message: '该歌曲为vip歌曲，试听30s，开通vip即可播放完整版',
                    type: 'warning'
                })
                pageObj.value = playList.playlist[index]
                return
            }
            const res = await getSongUrl(playList.playlist[index].id)
            playList.playlist[index].url = res.data[0].url
        }
        pageObj.value = playList.playlist[index]
    }, { immediate: true, deep: true }
)
watch(() => playList, (newVal) => {
    if (newVal.playlist.length == 1) {
        playIndex.playIndex = 0
        pageObj.value = playList.playlist[0]
    }
}, { immediate: true, deep: true })

//监听playList长度的变化
watch(() => playList.playlist.length, (newVal, oldVal) => {
    if (newVal == 0) {
        playMusic(false)
        isShowLyrics.value = false
    }
    if (newVal > oldVal) {
        const idx = newVal - 1
        visiblename.value = playList.playlist[idx].name
        visible.value = true
        setTimeout(() => {
            visible.value = false
        }, 2000)
    }
    if (newVal < oldVal) {
        if (newVal == playIndex.playIndex) {
            playIndex.playIndex -= 1
        }
        playIndex.playIndex += 1
        playIndex.playIndex -= 1
    }
}, { deep: true })
//监听playStatus.playStatus
watch(() => playStatus.playStatus, (newVal, oldVal) => {
    if (newVal) {
        music.value.play()
    } else {
        music.value.pause()
    }
}, { deep: true })
onMounted(() => {
    playStatus.playStatus = false
    // console.log('playbar');
})
//播放音乐
const playMusic = (status) => {
    playStatus.playStatus = status
    if (status) {
        try { music.value.play() }
        catch (e) {
            ElMessage({
                message: '该歌曲暂无版权，无法播放',
                type: 'warning'
            })
        }
    } else {
        music.value.pause()
    }
}
const play = () => {
    playStatus.playStatus = true
}
const changIndex = (num) => {
    // playIndex.playIndex += num
    //如果播放是第一首，点击上一首，播放最后一首
    if (playIndex.playIndex + num < 0) {
        playIndex.playIndex = playList.playlist.length - 1
    } else if (playIndex.playIndex + num > playList.playlist.length - 1) {
        //如果播放是最后一首，点击下一首，播放第一首
        playIndex.playIndex = 0
    } else {//否则，正常播放
        playIndex.playIndex += num
    }
    //如果当前页面在song页面，切换歌曲时，切换路由id
    if (route.name == 'song') {
        router.push(`/song?id=${playList.playlist[playIndex.playIndex].id}`)
    }
}
const formatTooltip = (val) => {
    return formatTime(val)
}
const volumeChange = () => {
    music.value.volume = volume.value / 100
}
const ended = () => {
    if (playIndex.playMode == 0) {
        changIndex(1)
    }
    if (playIndex.playMode == 1) {
        playIndex.playIndex = Math.floor(Math.random() * playList.playlist.length)
    }
    if (playIndex.playMode == 2) {
        music.value.currentTime = 0
        music.value.play()
    }
}
const timeupdate = (e) => {
    try {
        playE.playE = e.target.currentTime
        playtime.value = e.target.currentTime
    }
    catch (e) {
        // console.log(e)
    }
}
const playtimeinput = (val) => {
    music.value.currentTime = val
    playtime.value = val
}
const lyricsHanlder = () => {
    popoverBtn.value = lyricsBtnRef.value;
    if (clickType.value == 'lyrics') {
        isShowLyrics.value = !isShowLyrics.value;
    } else {
        isShowLyrics.value = true;
    }

    clickType.value = 'lyrics';
}
const lyricHanlder = (e) => {
    const composedPath = e.composedPath();
    if (composedPath.includes(popoverRef.value)) return;
    isShowLyrics.value = false;
}

const playlistHanlder = () => {
    popoverBtn.value = playlistBtnRef.value;
    // console.log(clickType.value, popoverBtn.value);
    if (clickType.value == 'playlist') {
        isShowLyrics.value = !isShowLyrics.value;
    } else {
        isShowLyrics.value = true;
    }

    clickType.value = 'playlist';
}
const clearSonglist = () => {
    playIndex.playIndex = 0
    playList.playlist = []
    pageObj.value = {
        album: {
            picUrl: ''
        },
        singer: [],
        name: '',
        duration: '',
        id: '',
        url: ''
    }
    playMusic(false)
    isShowLyrics.value = false

}


</script>

<style lang="less" scoped>
.play-bar {
    z-index: 999;
    height: 70px;
    width: calc(100vw - 260px);
    position: fixed;
    bottom: 0;
    left: 260px;

    .play-main {
        min-width: 800px;
        width: 80%;
        margin: 0 auto;
        height: 100%;
        background: #fff;
        box-shadow: 0 0px 10px rgba(0, 0, 0, .1);

        :deep(.el-slider) {
            transform: translateY(-50%);

            .el-slider__runway {
                background: transparent;
            }

            .el-slider__button {
                width: 12px;
                height: 12px;
            }

        }

        .play-bar-main {
            display: flex;
            font-size: 0;
            line-height: 0;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
            margin: 0 auto;
            transform: translateY(-35%);

            .bar-l {
                display: flex;
                justify-content: space-around;
                align-items: center;
                // width: 300px;

                .el-link {
                    .el-image {
                        width: 50px;
                        height: 50px;
                        border-radius: 5px;
                        margin-right: 10px;
                    }
                }

                .bar-name {
                    // display: flex;
                    // flex-direction: column;
                    // flex: 1;
                    height: 50px;
                    margin-right: 20px;

                    .el-link {
                        font-size: 14px;
                        color: black;
                        font-weight: 700;
                        line-height: 18px;
                        margin-left: 10px;
                        margin-bottom: 10px;
                    }

                    p {

                        // width: 60px;
                        // height: 20px;
                        // line-height: 18px;
                        display: block;
                        overflow: hidden;
                        width: 100%;
                        // white-space: nowrap;
                        text-overflow: ellipsis;

                        .el-link {
                            margin-left: 10px;
                            font-size: 12px;
                            color: #999;
                            font-weight: 600;
                        }
                    }
                }

                .bar-time {
                    flex: 1;
                    font-size: 14px;
                    color: #5f5f5f;
                    font-weight: 400;
                    height: 50px;
                    line-height: 50px;
                    text-align: center;
                }
            }

            .bar-m {
                // transform: translateX(-50%);
                flex: 1;

                .bar-control {
                    display: flex;
                    padding: 15px 0;
                    line-height: 1;
                    align-items: center;
                    justify-content: center;

                    i {
                        margin: 0 20px;
                        font-size: 25px;
                        cursor: pointer;
                        color: #666;
                    }
                }
            }

            .bar-r {
                // transform: translateX(-50%);

                .bar-oper {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    height: 100%;

                    i {
                        cursor: pointer;
                        font-size: 18px;
                        color: #89878a;
                        margin-left: 10px;
                    }

                    .volume-main {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        height: 100%;

                        .iconfont {
                            font-size: 25px;
                            color: #89878a;
                            margin-right: 10px;
                        }

                        :deep(.el-slider) {
                            width: 100px;
                            height: 100%;
                            margin-right: 10px;
                            transform: translateY(0);

                            .el-slider__runway {
                                background: #ebebeb;
                            }

                            .el-slider__bar {
                                background: #409eff;
                            }

                            .el-slider__button {
                                width: 8px;
                                height: 8px;
                            }
                        }
                    }

                    .lyric {

                        .lyric-btn {
                            display: inline-block;
                            margin-left: 10px;
                            // padding: 18px 5px 18px 15px;
                            font-size: 18px;
                            padding-bottom: 3px;
                            vertical-align: top;
                            color: #89878a;
                            cursor: pointer;
                        }
                    }

                    .playlist-main {
                        i {
                            margin-left: 10px;
                            // padding: 18px 5px 18px 15px;
                            line-height: 18px;
                            font-size: 25px;
                            color: #89878a;
                        }
                    }
                }
            }
        }
    }
}

.pop-main {
    min-height: 420px;

    .pop-header {
        display: flex;
        line-height: 10px;

        span {
            display: inline-block;
            flex: 1;
        }

        em {
            display: inline-block;
            padding-left: 10px;
            font-size: 12px;
            line-height: 14px;
            font-style: normal;
            font-weight: normal;
            color: #666;
            vertical-align: baseline;
        }

        .del-songlist {
            font-size: 14px;
            font-weight: normal;
            cursor: pointer;

            // .iconfont {
            //     font-size: 22px;
            //     vertical-align: middle;
            // }
        }
    }
}
</style>